﻿using System;
using System.Configuration;
using System.Web;

namespace MyOrganizer
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies[ConfigurationManager.AppSettings["CookieName"].ToString()] != null)
            {
                LogIn(true);
            }
        }

        protected void lnkLogIn_Click(object sender, EventArgs e)
        {
            LogIn(false);
        }

        protected void lnkSubmit_Click(object sender, EventArgs e)
        {
            var Bl = MyOrganizerModel.BusinessModel.GetInstance;
            Bl.AddUser(new MyOrganizerModel.Database.Users { Name = usernamesignup.Value, Password = passwordsignup_confirm.Value, Email = emailsignup.Value });
            ClientScript.RegisterClientScriptBlock(this.GetType(), "validation", "alert('Sucess please Log In.');", true);
        }

        private void LogIn(bool IsCookie)
        {
            var Bl = MyOrganizerModel.BusinessModel.GetInstance;
            int UserId = 0;
            string UserName = string.Empty;
            if (IsCookie)
            {
                UserId = Int32.Parse(Request.Cookies[ConfigurationManager.AppSettings["CookieName"].ToString()].Value.ToString());
                MyOrganizerModel.Database.Users UserInfo = Bl.GetUserById(UserId);
                UserName = UserInfo.Name;              
            }
            else
            {
                UserId = Bl.GetUser(username.Value, password.Value);
                if (UserId != 0)
                {
                    if (loginkeeping.Checked == true)
                    {
                        HttpCookie Cookie = new HttpCookie(ConfigurationManager.AppSettings["CookieName"].ToString());
                        Cookie.Value = UserId.ToString();
                        Cookie.Expires = DateTime.Now.AddDays(5);
                        Response.Cookies.Add(Cookie);
                    }
                    UserName = username.Value;
                }
            }
            Session["UserName"] = UserName;
            Session["UserId"] = UserId;
            Session.Timeout = 30;
            Response.RedirectToRoute("Home");
        }
    }
}